#region Copyright Notice
// 
// 
// Copyright (c) 2009-2010 Anindya Chatterjee
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// 
// 
// 
#endregion
using System;
using System.IO;
using Event.Plugin.Utility;
using IrrKlang;

namespace DesktopNotifier.Utility
{
    /// <summary>
    /// Play Sounds like wav, mp3 using NAudio
    /// </summary>
    public class SoundUtility
    {
        /// <summary>
        /// Plays sound from a sound file
        /// </summary>
        /// <param name="soundFile">Path of the sound file</param>
        public static void PlaySound(string soundFile)
        {
            var engine = new ISoundEngine();
            engine.Play2D(soundFile);
        }

        /// <summary>
        /// Plays sound from a unmanaged memory stream
        /// </summary>
        /// <param name="stream">Unmanaged memory string containg sound data</param>
        public static void PlaySound(Stream stream)
        {
            byte[] inputSound = StreamToByteArray(stream);
            var engine = new ISoundEngine();
            engine.AddSoundSourceFromMemory(inputSound, "alert");
            engine.Play2D("alert");
        }

        private static byte[] StreamToByteArray(Stream input)
        {
            var totalStream = new byte[0];
            var buffer = new byte[32 * 1024];
            int read;

            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                var streamArray = new byte[totalStream.Length + read];
                totalStream.CopyTo(streamArray, 0);
                Array.Copy(buffer, 0, streamArray, totalStream.Length, read);
                totalStream = streamArray;
            }

            return totalStream;
        }
    }
}